import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import {
  login as loginApi,
  logout as logoutApi,
  getUserInfo as getUserInfoApi,
  getTenantList as tenantList,
  switchTenant,
  getLogoIcon
} from "@/apis";
import type { UserInfo, roles as roleItem } from "@/apis";
import { setToken, clearToken, getToken } from "@/utils/auth";
import { resetHasRouteFlag } from "@/router/permission";
import { setLocalCache, removeLocalCache } from "@/utils/cache";
import webUrl from "@/assets/images/logo.png";
import config from "@/config/setting.json";

type TenantItem = {
  tenantId: string;
  tenantName: string;
  isExpired: boolean;
  expiredTime: string;
};
const storeSetup = () => {
  /**
   * @desc 用户信息
   */
  const userInfo = ref<Pick<UserInfo, any>>({});
  const name = computed(() => userInfo.value.nickName);
  const post = computed(() => userInfo.value.post);
  const mainDeptName = computed(() => userInfo.value.mainDeptName);
  const avatar = computed(() => userInfo.value.avatar);
  const tenantTypeCode = computed(() => userInfo.value.tenantTypeCode);
  const userId = computed(() => userInfo.value.userId);

  const token = ref(getToken() || "");
  const roles = ref<roleItem[]>([]); // 当前用户角色
  const permissions = ref<string[]>([]); // 当前角色权限标识集合

  /**
   * 用户租户信息
   */
  const tenantLists = ref<TenantItem[]>([]); // 租户列表
  const nowTenantName = computed(() => {
    if (tenantLists.value?.length) {
      const tenant = tenantLists.value.find(item => item.tenantId === userInfo.value.tenantId);
      if (!tenant) {
        tenantLists.value.push({
          tenantId: userInfo.value.tenantId,
          tenantName: userInfo.value.tenantName,
          isExpired: userInfo.value.isExpired,
          expiredTime: userInfo.value.expiredTime
        });
        return userInfo.value.tenantName;
      }
      return tenant?.tenantName;
    }
    return "";
  });

  /**
   * 是否到期
   */
  const isExpired = ref(false);
  const expiredTime = ref("");
  const openFinanceAccount = ref(false);
  const isTenantMaster = ref(false);
  /**
   * 重置token
   */
  const resetToken = () => {
    token.value = "";
    clearToken();
    resetHasRouteFlag();
  };

  /**
   * 登录
   * @param params
   */
  const login = async (params: any) => {
    const res = await loginApi(params);
    setToken(res.data.accessToken);
    setLocalCache("defaultActive", "/");
    setLocalCache("parentActive", "");
    token.value = res.data.accessToken;
  };

  /**
   * @desc 获取用户租户列表
   */
  const getTenantList = async () => {
    const res = await tenantList();
    const tenantData = res.data?.map((item: any) => {
      const tenantName = item.isExpired ? `${item.tenantName}(已到期)` : item.tenantName;
      return {
        ...item,
        tenantName
      };
    });
    tenantLists.value = tenantData || [];
    // console.log(tenantLists.value,"<<<<")
    // console.log(res, ">>>>租户列表");
  };

  /**
   * @desc 切换租户
   * @param tenantId
   */
  const router = useRouter();
  const changeTenant = async (tenantId: string) => {
    await switchTenant(tenantId);
    router.replace("/");
    setLocalCache("defaultActive", "/");
    setLocalCache("parentActive", "");
    removeLocalCache("expired");
    setTimeout(() => {
      location.reload();
    }, 100);
    Message.success("租户切换成功");
  };

  /**
   * @desc 退出
   */
  const logout = async () => {
    let favicon = document.querySelector('link[rel="icon"]') as any;
    await logoutApi();
    userInfo.value = {};
    token.value = "";
    roles.value = [];
    permissions.value = [];
    resetToken();
    removeLocalCache("defaultActive");
    removeLocalCache("parentActive");
    removeLocalCache("expired");
    removeLocalCache("logoIcon");
    document.title = config.title;
    favicon.href = webUrl;
  };

  /**
   * @desc 获取用户信息
   */
  const getInfo = async () => {
    let favicon = document.querySelector('link[rel="icon"]') as any;
    const res = await getUserInfoApi();
    // 是加盟商就更改icon图标等信息
    if (res.data?.agentTenantId && res.data?.isChainTenant) {
      const { data } = await getLogoIcon(res.data.agentTenantId);
      setLocalCache("logoIcon", JSON.stringify(data));
      document.title = data.navigationBarName ? data.navigationBarName : "家装通";
      favicon.href = data.mallWebpageIconUrl ? data.mallWebpageIconUrl : webUrl;
    } else {
      removeLocalCache("logoIcon");
      document.title = config.title;
      favicon.href = webUrl;
    }
    isExpired.value = res.data?.isExpired;
    expiredTime.value = res.data?.expiredTime;
    openFinanceAccount.value = res.data?.openFinanceAccount;
    isTenantMaster.value = res.data?.isTenantMaster;
    userInfo.value = {
      ...res.data?.user,
      mainDeptId: res.data?.mainDeptId,
      mainDeptName: res.data?.mainDeptName,
      isChainTenant: res.data?.isChainTenant,
      agentTenantId: res.data?.agentTenantId,
      agentTenantName: res.data?.agentTenantName
    };
    setLocalCache("userinfo", JSON.stringify(userInfo.value));
    if (res.data.roles?.length) {
      roles.value = res.data.roles;
      permissions.value = res.data.permissions;
    }
  };

  // 模拟用 临时模拟token过期
  const editToken = (value: string) => {
    token.value = value;
    setToken(token.value);
  };

  return {
    userInfo,
    userId,
    name,
    userPost: post,
    mainDeptName,
    avatar,
    tenantTypeCode,
    token,
    roles,
    permissions,
    tenantLists,
    nowTenantName,
    isExpired,
    expiredTime,
    openFinanceAccount,
    isTenantMaster,
    login,
    logout,
    getInfo,
    resetToken,
    editToken,
    getTenantList,
    changeTenant
  };
};

export const useUserStore = defineStore("user", storeSetup, {
  // persist: { paths: ["token", "roles", "permissions"], storage: localStorage }
  persist: { paths: ["token", "permissions"], storage: localStorage }
});
